<template>
  <div class="teacher-list-container">
    <!-- 搜索框 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入教师姓名或教研室进行搜索"
        style="width: 300px;"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button 
        type="primary" 
        @click="handleAdd"
        style="margin-left: 10px;"
      >
        新增
      </el-button>
    </div>

    <!-- 教师列表 -->
    <el-table
      :data="teacherList"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="name" label="姓名" width="200">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="office" label="所属教研室" width="300">
        <template #default="scope">
          <span>{{ scope.row.office }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" v-if="isAdmin">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" v-else>
        <template #default="scope">
          <span style="color: #999;">仅限管理员操作</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm._id ? '编辑教师信息' : '新增教师信息'"
      width="500px"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="editForm.name" placeholder="请输入教师姓名" />
        </el-form-item>
        <el-form-item label="教研室">
          <el-input v-model="editForm.office" placeholder="请输入所属教研室" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { teacherApi } from '@/api/teacherApi.js'

// 响应式数据
const teacherList = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const editDialogVisible = ref(false)
const editForm = ref({ _id: null, name: '', office: '' })

// 分页信息
const pagination = ref({
  currentPage: 1,
  size: 20,
  total: 0,
  pages: 0
})

// 模拟管理员权限（后续可从用户系统获取）
const isAdmin = ref(true)

// 加载教师列表数据
const loadTeacherList = async () => {
  try {
    loading.value = true
    const result = await teacherApi.getTeacherList({
      currentPage: currentPage.value,
      size: pageSize.value,
      otherParams: searchKeyword.value ? { keyword: searchKeyword.value } : {}
    })
    teacherList.value = result.list
    
    pagination.value = result.pagination
  } catch (error) {
    console.error('加载教师列表失败:', error)
    ElMessage.error('加载教师列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  loadTeacherList()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadTeacherList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadTeacherList()
}

// 编辑教师
const handleEdit = (row) => {
  editForm.value = { id: row.id, name: row.name, office: row.office }
  editDialogVisible.value = true
}

// 确认编辑
const confirmEdit = async () => {
  if (!editForm.value.name.trim()) {
    ElMessage.warning('请输入教师姓名')
    return
  }
  
  if (!editForm.value.office.trim()) {
    ElMessage.warning('请输入所属教研室')
    return
  }
  
  try {
    loading.value = true
    if (editForm.value.id) {
      // 编辑模式
      await teacherApi.updateTeacherInfo({
        id: editForm.value.id,
        name: editForm.value.name,
        office: editForm.value.office
      })
      ElMessage.success('成功修改')
    } else {
      // 新增模式
      await teacherApi.addTeacher({
        name: editForm.value.name,
        office: editForm.value.office
      })
      ElMessage.success('成功添加')
    }
    
    editDialogVisible.value = false
    loadTeacherList() // 重新加载数据
  } catch (error) {
    console.error('保存教师信息失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 删除教师
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除教师"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await teacherApi.deleteTeacher(row.id)
    ElMessage.success('删除成功')
    loadTeacherList() // 重新加载数据
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除教师失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 新增教师
const handleAdd = () => {
  editForm.value = { _id: null, name: '', office: '' }
  editDialogVisible.value = true
}

// 组件挂载时加载数据
onMounted(() => {
  loadTeacherList()
})
</script>

<style scoped>
.teacher-list-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 